package com.game.primitive.context;

import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PlayerManager {
	Logger logger = Logger.getLogger(PlayerManager.class);
	private static PlayerManager instance = new PlayerManager();

	private PlayerManager() {
	}

	public static PlayerManager getInst() {
		return instance;
	}

	/**
	 * 玩家缓存
	 */
	private Map<Integer, PrimitivePlayer> players = new ConcurrentHashMap<Integer, PrimitivePlayer>();

	public void clean() {
		players.clear();
	}

	/**
	 * 添加一个玩家
	 *
	 * @param player
	 */
	public void addPlayer(PrimitivePlayer player) {
		players.put(player.getUserId(), player);
	}

	/**
	 * 彻底删除一个玩家缓存对象（玩家退出房间、退出游戏）
	 *
	 * @param userID
	 */
	public void removePlayer(int userID) {
		if (!players.containsKey(userID)) {
			logger.error("移除玩家时没有找到" + userID);
			return;
		}
		players.remove(userID);
	}

	/**
	 * 获取所有的玩家缓存对象
	 *
	 * @return
	 */
	public Collection<PrimitivePlayer> getAllPlayers() {
		return players.values();
	}

	/**
	 * 获取指定的玩家缓存
	 *
	 * @param userID
	 * @return
	 */
	public PrimitivePlayer getPlayer(int userID) {
		if (userID == 0) {
			return null;
		}
		if (!players.containsKey(userID)) {
			return null;
		}
		return players.get(userID);
	}

	/**
	 * 得到桌子上的所有玩家，所有玩家
	 *
	 * @param tableId
	 * @return
	 */
	public List<PrimitivePlayer> getPlayerList(int tableId) {
		List<PrimitivePlayer> result = new ArrayList<PrimitivePlayer>();
		for (PrimitivePlayer player : players.values()) {
			if (player.getBattlefield() != null && player.getBattlefield().getId() == tableId) {
				result.add(player);
			}
		}
		return result;
	}
}
